package com.chensf.studydemo.common

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chensf.studydemo.R
import kotlinx.android.synthetic.main.fragment_load_more_demo.*
import kotlinx.android.synthetic.main.view_chat_msg_item.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class LoadMoreDemo :Fragment(){
    private val concatAdapter:ConcatAdapter = ConcatAdapter()
    private val chatMsgAdapter:ChatMsgAdapter = ChatMsgAdapter()
    private val headerAdapter = UpLoadMoreAdapter()
    private val footerAdapter = UpLoadMoreAdapter()
    private lateinit var layoutManager:LinearLayoutManager
    private var last = 21
    private var first = 19

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return layoutInflater.inflate(R.layout.fragment_load_more_demo,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        concatAdapter.addAdapter(headerAdapter)
        concatAdapter.addAdapter(chatMsgAdapter)
        concatAdapter.addAdapter(footerAdapter)

        button14.setOnClickListener {
            chatMsgAdapter.checkMode = !chatMsgAdapter.checkMode
            chatMsgAdapter.notifyItemRangeChanged(0,30)
        }

        layoutManager = LinearLayoutManager(requireContext())

        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = concatAdapter
        chatMsgAdapter.setData(createData(20))
        recyclerView.scrollToPosition(15)

        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    val lastVisibleItemPosition =
                        layoutManager.findLastCompletelyVisibleItemPosition()
                    //当前屏幕所看到的子项个数
                    val visibleItemCount = layoutManager.childCount
                    //当前RecyclerView的所有子项个数
                    val totalItemCount = layoutManager.itemCount
                    //滚动到底部
                    if (visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1) {
                        addLast()
                    }else if(layoutManager.findFirstVisibleItemPosition() == 0){
                        addFirst()
                    }
                }
            }
        })
    }

    private var isLoading = false
    private fun addLast(){
        lifecycleScope.launch(Dispatchers.Main){
            if(isLoading){
                return@launch
            }
            isLoading = true
            delay(2000)
            chatMsgAdapter.addLast(createData(last))
            last++
            isLoading = false
        }
    }

    private fun addFirst(){
        lifecycleScope.launch(Dispatchers.Main){
            if(first<17){
                return@launch
            }

            if(isLoading){
                return@launch
            }
            isLoading = true
            delay(2000)
            val list = createData(first)
            chatMsgAdapter.addFirst(list)

            val firstItemPosition = layoutManager.findFirstVisibleItemPosition()
            if(firstItemPosition==0){
                recyclerView.scrollToPosition(list.size+1)
            }
            first--

            if(first<17){
                concatAdapter.removeAdapter(headerAdapter)
            }

            isLoading = false
        }
    }

    private fun createData(data:Int): MutableList<String> {
        val list = mutableListOf<String>()
        for (index in 0..30){
            list.add("这是测试数据啊啊啊---$data")
        }
        return list
    }

    private class ChatMsgAdapter:RecyclerView.Adapter<ChatMsgHolder>(){
        private val data = mutableListOf<String>()
        var checkMode = false
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatMsgHolder {
            return ChatMsgHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.view_chat_msg_item, parent, false)
            )
        }

        override fun onBindViewHolder(holder: ChatMsgHolder, position: Int) {
            val item = data[position]
            holder.titleTV.text = item
            holder.checkBox.visibility = if(checkMode){
                View.VISIBLE
            }else{
                View.GONE
            }
        }

        override fun getItemCount(): Int {
            return data.size
        }

        fun setData(list: List<String>){
            data.clear()
            data.addAll(list)
            notifyItemRangeInserted(0,list.size)
        }

        fun addFirst(list:List<String>){
            data.addAll(0,list)
            notifyItemRangeInserted(0,list.size)
        }

        fun addLast(list:List<String>){
            data.addAll(list)
            notifyItemRangeInserted(data.size-list.size,list.size)
        }

    }

    private class ChatMsgHolder(itemView: View) :RecyclerView.ViewHolder(itemView){
        val titleTV:TextView = itemView.titleTV
        val checkBox:CheckBox = itemView.checkbox
    }

    private class UpLoadMoreAdapter:RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return LoadMoreHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.view_load_more, parent, false)
            )
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        }

        override fun getItemCount(): Int {
            return 1
        }

    }

    private class LoadMoreHolder(itemView: View) :RecyclerView.ViewHolder(itemView)
}